import config from "./config";

let requestTree = {};

//此方法会打断所有发送中请求
function abortRequest() {
	for (let name in requestTree) {
		requestTree[name].abort();
	}
	requestTree = {};
}

function request(options, toastInfo = {}) {
	const url = config.reqUrl + options.url;
	if (toastInfo.loading) {
		uni.showLoading({
			title: toastInfo.loading,
			mask: true,
		});
	}
	if (options.header) {
		options.header = options.header;
		if (!options.header["Content-Type"]) {
			options.header["Content-Type"] = "application/json";
		}
	} else {
		options.header = {
			"Content-Type": "application/json",
		};
	}
	if (uni.getStorageSync("token")) {
		options.header["token"] = uni.getStorageSync("token");
	}
	options.method = options.method || "GET";
	options.dataType = options.dataType || "json";
	return new Promise(function (resolve, reject) {
		requestTree[url] = uni.request({
			url, //请求地址
			header: options.header,
			method: options.method, //get为默认方法/POST
			dataType: "json",
			timeout: 30000,
			data: options.data,
			success: function (res) {
				delete requestTree[url];
				if (res.data.code === 1) {
					//请求成功
					if (toastInfo.isToast) {
						uni.showToast({
							title: res.data.msg,
							icon: "none",
							duration: 2000,
							mask: true,
						});
					} else {
						if (toastInfo.loading) {
							uni.hideLoading();
						}
					}
					resolve(res.data);
				} else if (res.data.code === 0) {
					uni.showToast({
						title: res.data.msg,
						icon: "none",
						duration: 2000,
						mask: true,
					});
					resolve(res.data);
				} else if (res.data.code === 401) {
					//token过期
					abortRequest();
					uni.showToast({
						title: "请登录",
						icon: "none",
						mask: true,
					});
					uni.removeStorageSync("userinfo");
					uni.removeStorageSync("token");
					uni.reLaunch({
						url: "/pages/login/login",
					});
				} else if (toastInfo.isToast) {
					//弹出提示给用户
					uni.showToast({
						title: res.data.msg,
						icon: "none",
						duration: 2000,
						mask: true,
					});
					reject(res.data);
				} else {
					if (toastInfo.loading) {
						uni.hideLoading();
					}
					reject(res.data);
				}
			},
			fail: function (err) {
				delete requestTree[url];
				if (err.statusCode === 401) {
					uni.showToast({
						title: "请重新登录",
						duration: 2000,
						icon: "none",
						mask: true,
					});
					uni.removeStorageSync("userinfo");
					uni.removeStorageSync("token");
					uni.removeStorageSync("is_lawyer");
					uni.reLaunch({
						url: "/pages/login/login",
					});
				} else if (res.data.code === 0) {
					uni.showToast({
						title: res.data.msg,
						icon: "none",
						duration: 2000,
						mask: true,
					});
					resolve(res.data);
				} else {
					uni.showToast({
						title: "请求失败",
						icon: "error",
						duration: 2000,
						mask: true,
					});
					reject(err);
				}
			}, //请求失败
		});
	});
}

export default request;